window.onload = function() {
  /*** PLUGIN ***/
  //META FOR MEDIA-SCREEN 
  var viewPortTag=document.createElement('meta');
  viewPortTag.id="viewport";
  viewPortTag.name = "viewport";
  viewPortTag.content = "width=device-width, initial-scale=1, maximum-scale=1";
  document.getElementsByTagName('head')[0].appendChild(viewPortTag);

  //TRANSITIONS
  var scale_transition = styleSupport( "transition" ),
    scale_duration = scale_transition+'-duration',
    scale_timing = scale_transition+'-timing-function',
    scale_delay = scale_transition+'-delay';;

  function styleSupport( prop ) {
    var vendorProp, supportedProp,
    capProp = prop.charAt(0).toUpperCase() + prop.slice(1),
    prefixes = [ "Moz", "Webkit", "O", "ms" ],
    newprefixes = [ "-moz-", "-webkit-", "-o-", "-ms-" ],
    div = document.createElement( "div" );

    if ( prop in div.style ) {
      supportedProp = prop;
    } else {
      for ( var i = 0; i < prefixes.length; i++ ) {
        vendorProp = prefixes[i] + capProp;
        if ( vendorProp in div.style ) {
          supportedProp = newprefixes[i]+prop;
          break;
        }
      }
    }

    div = null;
    return supportedProp;
  }

  setDuration = function(the, time) {
    the.style[scale_duration] = time+'ms';
  }

  getDuration = function(the) {
    return the.style[scale_duration];
  }

  setTiming = function(the,timing) {
    the.style[scale_timing] = timing;
  }

  getTiming = function(the) {
    return the.style[scale_timing];
  }

  setDelay = function(the,delay) {
    the.style[scale_delay] = delay+'ms';
  }

  getDelay = function(the) {
    return the.style[scale_delay];
  }

  function getHash(len) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    for(var i = 0;i < len;i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
  }


  var scaleImage = function(selector, classname, initialWidth) {

    var obj = this;

    //Selecting Image
    var sel = !!(typeof selector === 'string') && selector.substring(1);
    this.image;

    if (selector[0] === '.') {
      this.image = document.getElementsByClassName(sel)[0];
    } else if (selector[0] === '#'){
      this.image = document.getElementById(sel);
    } else {
      this.image = selector;
    }

    //CREATE MASK
    this.id = getHash(10);

    ///HTML
    var mask = document.createElement('div');
    mask.id = this.id;
    this.image.setAttribute('id-mask', this.id);
    this.image.insertAdjacentHTML('afterend', mask.outerHTML);
    this.mask = document.getElementById(this.id);

    ///CSS
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '#'+this.id+'{ background-image: url('+this.image.src+'); background-repeat: no-repeat;height: auto;position: absolute;width: auto;}';
    document.getElementsByTagName('head')[0].appendChild(style);

    var pathStyle = window.getComputedStyle(this.image);
    console.log(pathStyle.width);
    console.log(pathStyle.height);

    ///UPDATE MASK
    this.updateMask = function() {
      var pathStyle = window.getComputedStyle(this.image);
      this.height = pathStyle.width;
      this.width = pathStyle.width;
      this.mask.style.height = this.height;
      this.mask.style.width = this.width;
      this.mask.style.left = this.image.offsetLeft+'px';
      this.mask.style.top = this.image.offsetTop+'px';
      this.mask.style.backgroundSize = this.width;
    }

    this.setWidth = function(width) {
      if (width[width.length-1] === '%') {
        var newW = parseFloat(width);
        var actualW = (parseFloat(this.width) * newW)/100;
        this.mask.style.width = actualW+'px';
      } else if (typeof width === "string" && width.substring(width.length-2) === 'px') {
        this.mask.style.width = width;
      } else {
        this.mask.style.width = width + 'px';
      }
    }

    this.TransitionDuration = getDuration(this.mask);
    this.TransitionTiming = getTiming(this.mask);

    this.reset = function() {
      var duration = parseFloat(getDuration(this.mask));
      var delay = parseFloat(getDelay(this.mask));
      var $this = this;
      setDuration(this.mask,0);
      setDelay(this.mask,0);
      this.mask.classList.remove(this.cssClass);
      this.setWidth(0);
      setTimeout(function(){
        !!duration && setDuration($this.mask,duration);
        !!delay && setDelay($this.mask,delay);
        $this.setWidth('100%');
      },100);
      
    }

    window.addEventListener("resize", function(){
      obj.reset();
      obj.updateMask();
    });

    this.updateMask();
    initialWidth  = initialWidth != undefined ? initialWidth : 0;
    this.setWidth(initialWidth);
    setTimeout(function(){
      if (!!classname) {
        obj.mask.classList.add(classname);
        obj.cssClass = classname;
      }
    },800);


    obj.mask.addEventListener('webkitTransitionEnd', function(){

    });
  }
  //END PLUGIN


  // PLUGIN CALL
  var images = [new scaleImage('#path1'),
                new scaleImage('#path2'),
                new scaleImage('#path3')];


  /*** DATA-GUI ***/
  var MapPath = function() {
    this.delay = 0;
    this.duration = 500; //ms
    this.timing = 'linear';
    this.testSinglePath = function(){};

    this.TESTALL = function(){
      for(var i = 0; i < images.length; i++) {
        var obj = images[i];
        obj.reset();
      }
    }
  };

  var mapPath = new MapPath();
  var gui = new dat.GUI();
  
  for(var i = 0; i < images.length; i++) {
    var obj = images[i];

    var f = gui.addFolder(obj.image.getAttribute('alt').split(' ')[obj.image.getAttribute('alt').split(' ').length-1]);

    var dl = f.add(mapPath, 'delay', 0, 3000);

    var d = f.add(mapPath, 'duration', 0, 3000);
    
    var t = f.add(mapPath, 'timing', 
                  { Linear: 'linear', Ease: 'ease', EaseIn: 'ease-in',
                    EaseOut: 'ease-out', EaseInOut: 'ease-in-out', 
                    CubicBezier: 'cubic-bezier(1,-0.22,0,1.12)' } );

    var test = f.add(mapPath,'testSinglePath');

    test.obj = dl.obj = d.obj = t.obj = images[i];

    setDelay(dl.obj.mask, mapPath.delay);
    setDuration(d.obj.mask, mapPath.duration);
    setTiming(t.obj.mask, mapPath.timing );
    t.obj.reset();

    test.onChange(function(){
      this.obj.reset();
    });

    dl.onChange(function(value){
      setDelay(this.obj.mask, value);
    });

    d.onChange(function(value){
      setDuration(this.obj.mask, value);
    });

    t.onChange(function(value){
      setTiming(this.obj.mask, value);
    });

  }
  gui.add(mapPath,'TESTALL');
}